var borderContainer;
var tabContainer;
var dlg_deleteProject;
var dlg_deleteTask;
var dlg_editTask;
var dlg_newComment;
var dlg_newProject;
var dlg_newTask;
var menu_projectItem;
var menu_taskList;
var prj_Stores = [];
var prj_Models = [];
var prj_Trees = [];
var projectTooltips = [];

var hideLoader = function() {
	dojo.fadeOut({
		node:"preloader",
		onEnd: function(){
			dojo.style("preloader", "display", "none");
		}
	}).play();
}

function initWidgets() {
	borderContainer = dijit.byId("borderContainer");
	tabContainer = dijit.byId("tabContainer");
	dojo.connect( tabContainer, "removeChild", function( child ) {
		if ( child.attr("projectid") != undefined && child.attr("projectid") != null ) {
			var projectid = child.attr("projectid");
			menu_taskList.unBindDomNode( prj_Trees[projectid].domNode );
			prj_Trees[projectid].destroyRecursive();
			prj_Trees[projectid] = null;
			prj_Stores[projectid].close();
			prj_Stores[projectid] = null;
			prj_Models[projectid].destroy();
			prj_Models[projectid] = null;
		}
		if ( child.attr("title") == "Projects" ) {
			if ( projectTooltips.length > 0 ) {
				dojo.forEach( projectTooltips, function( value, key ) {
					value.destroyRecursive();
				});
			}
		}
		var children = tabContainer.getChildren();
		tabContainer.selectChild( children[children.length - 1]);
		children = null;
	});
	menu_projectItem = dijit.byId("projectItemMenu");
	dojo.connect( menu_projectItem, "_openMyself", function(e) { menu_projectItem.attr("projectnode", e.target); });
	dojo.connect( menu_projectItem, "onOpen", function(e) {
		menu_projectItem.getChildren().forEach( function(o) {
			dojo.toggleClass( o.domNode, "dijitMenuItemHover", false );
			dojo.toggleClass( o.domNode, "dijitMenuItemSelected", false );
		});
	});
	menu_taskList = dijit.byId("taskListMenu");
	dojo.connect( menu_taskList, "_openMyself", function(e) {
		var tn = dijit.getEnclosingWidget(e.target);
		var item = tn.item;
		var parentnode = tn.getParent();
		var parentid;
		if ( parentnode == null ) parentid = 0;
		else if ( parentid == "root" ) parentid = 0;
		else parentid = parentnode.item.id[0] * 1;
		menu_taskList.attr("taskparent", parentid);
		menu_taskList.attr("taskitem", item);
		menu_taskList.attr("taskproject", tabContainer.selectedChildWidget.projectid);
	});
	dojo.connect( menu_taskList, "onOpen", function(e) {
		menu_taskList.getChildren().forEach( function(o) {
			dojo.toggleClass( o.domNode, "dijitMenuItemHover", false );
			dojo.toggleClass( o.domNode, "dijitMenuItemSelected", false );
		});
	});
	dlg_deleteProject = dijit.byId("dlg_deleteProject");
	dlg_deleteTask = dijit.byId("dlg_deleteTask");
	dlg_editTask = dijit.byId("dlg_editTask");
	dlg_newComment = dijit.byId("dlg_newComment");
	dlg_newProject = dijit.byId("dlg_newProject");
	dlg_newTask = dijit.byId("dlg_newTask");
	dojo.connect( dlg_newProject, "onCancel", function(e) { this.reset(); } );
}

/*****
 *		'Delete Project' dialog functions
 *****/
function showDeleteProject() {
	var projectnode = menu_projectItem.attr("projectnode");
	dojo.attr( dojo.byId("dpName"), "innerHTML", dojo.attr(projectnode, "projectname") );
	dojo.attr( dojo.byId("dpId"), "value", dojo.attr(projectnode, "projectid") );
	dlg_deleteProject.show();
}

function submitDeleteProject() {
	var projectid = dojo.attr( dojo.byId("dpId"), "value" );
	showLoading();
	dojo.xhrPost({
		url: "projects.php",
		handleAs: "json",
		content: { action: "deleteProject", projectid: projectid },
		load: function(data, ioargs) {
			if ( data.result == 0 ) {
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == 1 ) {
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				tabContainer.getChildren().forEach( function(n) {
					if ( n.attr("title") == "Projects" ) {
						dojo.query("div.projectInfo").forEach( function(n) { menu_projectItem.unBindDomNode(n); } );
						tabContainer.removeChild(n);
						n.destroyRecursive();
					}
				});
				displayProjects();
			}
			hideLoading();
		},
		error: function(data, ioargs) {
			hideLoading();
		}
	});
}

function closeDeleteProject() {
	dlg_deleteProject.hide();
}

/*****
 *		Delete Task dialog functions
 *****/
function showDeleteTask() {
	dojo.attr( dojo.byId("dtProjectID"), "value", menu_taskList.attr("taskproject") );
	dojo.attr( dojo.byId("dtNodeID"), "value", menu_taskList.attr("taskitem").id[0] );
	dojo.attr( dojo.byId("dtName"), "innerHTML", menu_taskList.attr("taskitem").name[0] );
	if ( menu_taskList.attr("taskitem").children.length > 0 ) dojo.style( dojo.byId("dtOptionTable"), "display", "inline" );
	else dojo.style( dojo.byId("dtOptionTable"), "display", "none" );
	dlg_deleteTask.show();
}

function closeDeleteTask() {
	dlg_deleteTask.hide();
}

function submitDeleteTask() {
	var taskid = dojo.attr( dojo.byId("dtNodeID"), "value" );
	var projectid = dojo.attr( dojo.byId("dtProjectID"), "value" );
	var childoption = dojo.attr( dojo.query( "input[name=dtChildOption]:checked" )[0], "value" );
	showLoading();
	dojo.xhrPost({
		url: "nodes.php",
		handleAs: "json",
		content: { action: "deleteNode", projectid: projectid, taskid: taskid, childoption: childoption },
		load: function( data, ioargs ) {
			if ( data.result == 0 ) {
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == 1 ) {
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				getTaskTree( tabContainer.selectedChildWidget.projectname, tabContainer.selectedChildWidget.projectid );
			}
			hideLoading();
		},
		error: function( data, ioargs ) {
			hideLoading();
		}
	});
}

/*****
 *		New Project dialog functions
 *****/
function closeNewProject() { 
	dlg_newProject.hide();
	dlg_newProject.reset(); 
}
function submitNewProject( d ) {
	var data = d.attr('value');
	d.reset();
	showLoading();
	dojo.xhrPost({
		url: "projects.php",
		handleAs: "json",
		content: { action: "newProject", name: ""+data.npName, desc: ""+data.npDesc },
		load: function(data, ioargs) {
			if ( data.result == 0 ) { 
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == 1 ) { 
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				tabContainer.getChildren().forEach( function(n) {
					if ( n.attr("title") == "Projects" ) {
						dojo.query("div.projectInfo").forEach( function(n) { menu_projectItem.unBindDomNode(n); } );
						tabContainer.removeChild(n);
						n.destroyRecursive();
					}
				});
				displayProjects();
			}
			hideLoading();
		},
		error: function(data, ioargs) {
			hideLoading();
		}
	});
}

/*****
 *		Edit Task dialog functions
 *****/

function showEditTask() {
    dojo.attr( dojo.byId("etTaskID"), "value", menu_taskList.attr("taskitem").id[0] );
    dijit.byId("etName").attr("value", menu_taskList.attr("taskitem").name[0]);
    dlg_editTask.show();
}

function submitEditTask() {
    dlg_editTask.hide();
	var nodeid = dojo.attr( dojo.byId("etTaskID"), "value");
	var nodename = dijit.byId("etName").attr("value");
	dlg_editTask.reset();
	showLoading();
	dojo.xhrPost({
		url: "nodes.php",
		handleAs: "json",
		content: { action: "editNode", nodeid: nodeid, nodename: nodename},
		load: function( data, ioargs ) {
			if ( data.result == 0 ) { 
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == 1 ) { 
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				getTaskTree( tabContainer.selectedChildWidget.projectname, tabContainer.selectedChildWidget.projectid );
			}
			hideLoading();	
		},
		error: function( data, ioargs ) {
			hideLoading();
		}
	})
}

function closeEditTask() {
    dlg_editTask.hide();
    dlg_editTask.reset();
}

/*****
 *		New Task dialog functions
 *****/
function showNewTask() {
	dojo.attr( dojo.byId("ntProjectID"), "value", menu_taskList.attr("taskproject") );
	dojo.attr( dojo.byId("ntParentID"), "value", menu_taskList.attr("taskparent") );
	dlg_newTask.show();
}

function showInsertTask() {
	dojo.attr( dojo.byId("ntProjectID"), "value", menu_taskList.attr("taskproject") );
	dojo.attr( dojo.byId("ntParentID"), "value", menu_taskList.attr("taskitem").id[0] );
	dlg_newTask.show();
}

function submitNewTask(d) {
	var data = d.attr("value");
	d.reset();
	var postdata = {
		action: "addNode",
		name: data.ntName,
		desc: data.ntDesc,
		projectid: dojo.attr(dojo.byId("ntProjectID"),"value"),
		parentid: dojo.attr(dojo.byId("ntParentID"),"value")
	};
	showLoading();
	dojo.xhrPost({
		url: "nodes.php",
		handleAs: "json",
		content: postdata,
		load: function(data, ioargs) {
			if ( data.result == 0 ) { 
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == 1 ) { 
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				getTaskTree( tabContainer.selectedChildWidget.projectname, tabContainer.selectedChildWidget.projectid );
			}
			hideLoading();
		},
		error: function(data, ioargs) {
			hideLoading();
		}
	});
}

function closeNewTask() {
	dlg_newTask.hide();
	dlg_newTask.reset();
}

/*****
 *		New Comment dialog functions
 *****/
function showNewComment( taskid ) {
	dojo.attr( dojo.byId("ncTaskID"), "value", taskid );
	dlg_newComment.show();
}

function closeNewComment() {
	dlg_newComment.hide();
	dlg_newComment.reset();
}

function submitNewComment() {
	var taskid = dojo.attr( dojo.byId("ncTaskID"), "value");
	var content = dijit.byId("ncContent").attr("value");
	dlg_newComment.reset();
	showLoading();
	dojo.xhrPost({
		url: "comments.php",
		handleAs: "json",
		content: { action: "addComment", nodeid: taskid, content: content },
		load: function(data, ioargs) {
			if ( data.result == 0 ) { 
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == 1 ) { 
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				var value = data.comment;
				dojo.create("div",{id: "taskComment-"+value.id, class: "taskComment", innerHTML: value.content }, dojo.byId("taskComments-"+value.nodeID), "first");
				dojo.create("div",{class: "commentDate", innerHTML: value.createdOn}, dojo.byId("taskComment-"+value.id), "last");
			}
			hideLoading();			
		},
		error: function(data, ioargs) {
			hideLoading();
		}
	})
}

function openProject( name, id ) {
	tabContainer.getChildren().forEach( function(n) {
		if ( n.attr("title") == name ) {
			tabContainer.removeChild(n);
			n.destroyRecursive();
		}
	});
	var content = "<h1>"+name+"</h1><div class='dijitMenuBar dijitMenuBarActive buttonBar' id='buttonBar-"+id+"'></div><div id='taskTree-"+id+"'></div>";
	var pane = new dijit.layout.ContentPane({ title: name, closable: "true", content: content, id: "projectPane-"+id, projectpane: "true" });

	tabContainer.addChild(pane);
	tabContainer.selectChild(pane);
	dojo.attr( pane, "projectid", id );
	dojo.attr( pane, "projectname", name );

	var buttonBar = dojo.byId("buttonBar-"+id);
	dojo.create("button", {id: "toggleCompleted-"+id}, buttonBar, "first");
	dojo.create("label", {id: "seperator"}, buttonBar, "last");
	dojo.create("button", {id: "btnInsertTask-"+id}, buttonBar, "last");
	dojo.create("button", {id: "btnAddTask-"+id}, buttonBar, "last");
	dojo.create("label", {id: "seperator"}, buttonBar, "last");
	dojo.create("button", {id: "btnEditTask-"+id}, buttonBar, "last");
	dojo.create("button", {id: "btnDeleteTask-"+id}, buttonBar, "last");

	var btnInsertTask = new dijit.form.Button({showLabel: false, iconClass: "todojoIcon todojoIconDisabled iconFolderAdd"}, "btnInsertTask-"+id);
	var btnAddTask = new dijit.form.Button({showLabel: false, iconClass: "todojoIcon iconTaskAdd"}, "btnAddTask-"+id);
	var btnEditTask = new dijit.form.Button({showLabel: false, iconClass: "todojoIcon todojoIconDisabled iconPencil"}, "btnEditTask-"+id);
	var btnDeleteTask = new dijit.form.Button({showLabel: false, iconClass: "todojoIcon todojoIconDisabled iconBin"}, "btnDeleteTask-"+id);
	var btnToggle = new dijit.form.ToggleButton({
		showLabel: true,
		checked: false,
		onChange: function(val) {
			if ( val == true ) {
				getTaskTree( name, id );
				this.attr('iconClass', "todojoIcon iconConfirm");
			} else {
				getTaskTree( name, id );
				this.attr('iconClass', "todojoIcon iconCancel");
			}
		},
		label: "Show Completed",
		iconClass: "todojoIcon iconCancel"
	}, "toggleCompleted-"+id);

	getTaskTree( name, id );
}

function enableTaskListButtons( id ) {
	dijit.byId("btnInsertTask-"+id).attr('iconClass', 'todojoIcon iconFolderAdd');
	dijit.byId("btnEditTask-"+id).attr('iconClass', 'todojoIcon iconPencil');
	dijit.byId("btnDeleteTask-"+id).attr('iconClass', 'todojoIcon iconBin');
}

function disableTaskListButtons( id ) {
	dijit.byId("btnInsertTask-"+id).attr('iconClass', 'todojoIcon todojoIconDisabled iconFolderAdd');
	dijit.byId("btnEditTask-"+id).attr('iconClass', 'todojoIcon todojoIconDisabled iconPencil');
	dijit.byId("btnDeleteTask-"+id).attr('iconClass', 'todojoIcon todojoIconDisabled iconBin');
}

function openTask( item ) {
	//console.log( "Opening task "+id+", '"+name+"'" );
	tabContainer.getChildren().forEach( function(n) {
		if ( n.attr("title") == "View Task" && n.attr("taskid") == item.id[0] ) {
			tabContainer.removeChild(n);
			n.destroyRecursive();
		}
	});
	var content = "<h1>View Task</h1><hr><div id='taskInfo-"+item.id[0]+"'></div><h1>Comments</h1><hr><button id='btn_addComment-"+item.id[0]+"'></button><div id='taskComments-"+item.id[0]+"'></div>";
	var pane = new dijit.layout.ContentPane({ title: "View Task", closable: "true", content: content, id: "taskPane-"+item.id[0], taskpane: "true", taskid: item.id[0] });
	tabContainer.addChild(pane);
	tabContainer.selectChild(pane);
	var btn_addComment = new dijit.form.Button({
		label: "Add Comment",
		onClick: function() { showNewComment( item.id[0] ); }
	}, "btn_addComment-"+item.id[0] );
	
	var params = { action: "getNode", nodeid: item.id[0] }
	showLoading();
	dojo.xhrGet({
		url: "nodes.php",
		handleAs: "json",
		content: params,
		load: function(data, ioargs) {
			if ( data.result == 0 ) { 
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == "1" ) { 
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				var node = data.node;
				var content = "<span class='taskName'>"+node.name+"</span><br/>";
				if ( data.description != "" ) content = content + "<p class='taskDesc'>"+node.description+"</p>";
				content = content + "<div class='taskDates'>created: "+node.createdOn+" | updated: "+node.updatedOn;
				dojo.create( "div", { innerHTML: content }, dojo.byId("taskInfo-"+node.id), "last" );
				if ( data.comments != null && data.comments != undefined && data.comments.length > 0 ) {
					dojo.forEach( data.comments, function(value,key){
						dojo.create("div",{id: "taskComment-"+value.id, class: "taskComment", innerHTML: value.content }, dojo.byId("taskComments-"+value.nodeID), "first");
						dojo.create("div",{class: "commentDate", innerHTML: value.createdOn}, dojo.byId("taskComment-"+value.id), "last");
						dojo.create("div",{class: "commentButtons", innerHTML: "<a href='#'><div class='todojoIcon iconBin' onClick='deleteComment("+value.id+");return false;' title='Delete Comment'></div></a>"}, dojo.byId("taskComment-"+value.id), "last");
					});
				}
			}
			hideLoading();
		},
		error: function(data, ioargs) {
			showError( "Ajax error: " + data );
			console.log( data );
		    hideLoading();
		}
	});
}

function deleteComment( commentID ) {
	showLoading();
	dojo.xhrPost({
		url: "comments.php",
		handleAs: "json",
		content: { action: "deleteComment", commentid: commentID },
		load: function(data, ioargs){
			if ( data.result == 0 ) { 
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == "1" ) { 
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				var commentDiv = dojo.byId("taskComment-"+commentID);
				dojo.fadeOut({
					node: commentDiv,
					onEnd: function() {
						dojo.destroy( commentDiv );
					}
				}).play();
			}
			hideLoading();
		},
		error: function(data, ioargs) {
			hideLoading();
		}
	})
}

function getTaskTree( name, id ) {
	if ( prj_Trees[id] != null && prj_Trees[id] != undefined ) {
		menu_taskList.unBindDomNode( prj_Trees[id].domNode );
		prj_Trees[id].destroyRecursive();
		prj_Trees[id] = null;
		dojo.create("div", { id: "taskTree-"+id }, "projectPane-"+id, "last" );
	}
	if ( prj_Stores[id] != null && prj_Stores[id] != undefined ) {
		prj_Stores[id].close();
		prj_Stores[id] = null;
	}
	if ( prj_Models[id] != null && prj_Models[id] != undefined ) {
		prj_Models[id].destroy();
		prj_Models[id] = null;
	}
	var showCompleted = dijit.byId("toggleCompleted-"+id).checked;
	if ( showCompleted == true ) showCompleted = "completed=1&"; else showCompleted = "completed=0&";
	prj_Stores[id] = new dojo.data.ItemFileWriteStore({
		url: "nodes.php?action=getProjectNodes&"+showCompleted+"projectid="+id,
		onComplete: function(items, request) {
			console.log("done!");
		}
	});
	prj_Models[id] = new dijit.tree.TreeStoreModel({
		store: prj_Stores[id],
		query: {type: "node"},
		queryOptions: {ignoreCase: true, deep: true},
		rootId: "root",
		rootLabel: name,
		childrenAttrs: ["children"]
	});
	prj_Trees[id] = new dijit.Tree({
		model: prj_Models[id]
	}, "taskTree-"+id);
	menu_taskList.bindDomNode( prj_Trees[id].domNode );
	dojo.connect( prj_Trees[id], "onDblClick", function( item, widget ) {
		openTask( item );
	});
	dojo.connect( prj_Trees[id], "_onNodeFocus", function( node ) {
		enableTaskListButtons(id);
	});
	dojo.connect( prj_Trees[id], "_onBlur", function() {
		disableTaskListButtons(id);
		prj_Trees[12].lastFocused.setSelected(false);
	});

}

function displayProjects() {
	tabContainer.getChildren().forEach( function(n) {
		if ( n.attr("title") == "Projects" ) {
			dojo.query("div.projectInfo").forEach( function(n) { menu_projectItem.unBindDomNode(n); } );
			tabContainer.removeChild(n);
			n.destroyDescendants();
			n.destroyRecursive();
		}
	});
	var content = "<h1>Projects</h1><hr><div id='openProjectList'></div>";
	var pane = new dijit.layout.ContentPane({ title: "Projects", closable: "true", content: content });
	tabContainer.addChild(pane);
	tabContainer.selectChild(pane);
	showLoading();
	//var projectsDiv = dojo.query("div#openProjectList", pane.domNode);
	var projectsDiv = dojo.byId("openProjectList");
	dojo.xhrGet({
		url: "projects.php",
		handleAs: "json",
		content: { action: "getProjects" },
		load: function( data, ioargs ) {
			if ( data.result == 0 ) {
				if ( data.errorMsg != undefined ) showError( data.errorMsg );
			} else if ( data.result == 1 ) {
				if ( data.successMsg != undefined ) showSuccess( data.successMsg );
				if ( data.projects != undefined && data.projects.length > 0 ) {
					var content = "";
					for ( var i = 0; i < data.projects.length; i++ ) {
						var record = data.projects[i];
						var projectDiv = dojo.create("div", { class: "projectInfo", id: "projectItem-"+record.projectid, "projectname": record.projectname, "projectid": record.projectid, style: { opacity: "0" } }, projectsDiv, "first");
						dojo.create("a", { href: "#", onclick: "openProject('"+record.projectname+"', "+record.projectid+");return false;", innerHTML: record.projectname }, projectDiv, "last");
						dojo.fadeIn({node: projectDiv}).play();
						var projectTooltip = new dijit.Tooltip({ tooltipSubject: "project", label: "<b>Description:</b><br />"+record.projectdesc, connectId: ["projectItem-"+record.projectid], position: ["below","above"] });
						projectTooltips.push( projectTooltip );
						menu_projectItem.bindDomNode( projectDiv );
					}
				}
			}
			hideLoading();
		},
		error: function( data, ioargs ) {
			hideLoading();
		}
	})
}

function showLoading() {
	dojo.query("img#loading").style("display", "inline");
}

function hideLoading() {
	dojo.query("img#loading").style("display", "none");
}

function showSuccess( msg ) {
	dijit.byId('toaster_div').setContent( msg, 'message' );
	dijit.byId('toaster_div').show();
}

function showError( msg ) {
	dijit.byId('toaster_div').setContent( msg, 'error' );
	dijit.byId('toaster_div').show();
}
